package com.iot.common.core.util;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class EncryptUtil {
	
    public static void main(String[] args) throws NoSuchAlgorithmException {

        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(512);
        KeyPair pair = keyGen.generateKeyPair();

        byte[] publicBytes = pair.getPublic().getEncoded();
        byte[] privateBytes = pair.getPrivate().getEncoded();

        System.out.println("public key: " + base64Encode(publicBytes));
        System.out.println("private key: " + base64Encode(privateBytes));
        
        
         KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); 
         keyGenerator.init(128); 
         SecretKey secretKey =keyGenerator.generateKey(); //获取密钥

         byte[] keyBytes =secretKey.getEncoded(); //将密钥字符串化

         //公开密钥加密
         // 解决的办法是将对称加密的密钥使用非对称加密的公钥进行加密，然后发送出去，接收方使用私钥进行解密得到对称加密的密钥，然后双方可以使用对称加密来进行沟通。
        
    }

    static String base64Encode(byte[] bytes) {

        return Base64.getEncoder().encodeToString(bytes);
    }

}
